package com.mall.pay.services;


import com.alipay.api.domain.OrderDetail;
import com.mall.order.OrderCoreService;
import com.mall.order.dto.OrderDto;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.user.IMemberService;
import com.mall.user.dto.QueryMemberResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Member;
import java.util.Date;

@Service
@Slf4j
@Component
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Reference(retries = 0,check = false)
    OrderCoreService orderCoreService;

    @Reference(retries = 0,check = false)
    IMemberService memberService;

    @Autowired
    PaymentMapper paymentMapper;


    /*
         获取支付二维码
     */
    @Override
    @Transactional
    public AlipaymentResponse aliPay(PaymentRequest request) {
        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        //获取用户相关信息
        QueryMemberResponse member = memberService.queryMemberByUserName(request.getUsername());
        if (member == null) {
            // 获取支付二维码失败
            alipaymentResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
            return alipaymentResponse;
        }
        //设置正确的 userId
        request.setUserId(member.getId());


        // 1. 调用当面付Demo中的test_precreate方法，获取支付二维码
        String codeFileName = payHelper.test_trade_precreate(request);


        // 2. 判斷二维码是否获取成功
        if (codeFileName == null) {
            // 获取支付二维码失败
            log.info("获取二维码失败");
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }

        // 获取支付二维码成功
        // 1. 要在tb_payment插入一条记录，记录订单的支付信息， PayResultEnum.PAY_PROCESSING（支付处理中）


        Payment payment = new Payment();
        //支付处理中
        payment.setStatus("1");
        payment.setCreateTime(new Date());
        payment.setOrderId(request.getTradeNo());
        payment.setPayWay(request.getPayChannel());
        payment.setOrderAmount(request.getTotalFee());
        payment.setPayerUid(member.getId());
        payment.setPayerName(member.getUsername());
        payment.setRemark("支付宝支付");
        payment.setUpdateTime(new Date());
        payment.setPayerAmount(request.getTotalFee());
        int insert = paymentMapper.insert(payment);
        if (insert != 1) {
            // 插入异常
            log.info("插入数据库异常");
            alipaymentResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
            return alipaymentResponse;
        }
        // 2. 返回二维码，并设置响应结果信息
        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        alipaymentResponse.setQrCode(codeFileName);
        return alipaymentResponse;
    }

    /*
           查询订单的支付结果
     */
    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {
        // 调用test_trade_query方法，查询指定的订单支付结果
        boolean paySuccess = payHelper.test_trade_query(request);
        //更新状态
        AlipayQueryRetResponse alipayQueryRetResponse = new AlipayQueryRetResponse();

        // 判断是否支付成功
        if (paySuccess) {
            // 1. 修改tb_payment中的订单支付记录的支付结果 ->PayResultEnum.PAY_SUCCESS
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId", request.getTradeNo());
            Payment payment = new Payment();
            payment.setOrderId(request.getTradeNo());
            payment.setStatus(PayReturnCodeEnum.SUCCESS.getCode());
            int i = paymentMapper.updateByExampleSelective(payment, example);
            if (i != 1) {
                alipayQueryRetResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
                return alipayQueryRetResponse;
            }
            //  调用订单服务，完成以下功能

            // 2. 修改订单的状态为已支付
            boolean isUpdated = orderCoreService.payOrderSuccess(request.getTradeNo());
            if (!isUpdated) {
                log.info("更新数据出问题");
                alipayQueryRetResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
                return alipayQueryRetResponse;
            }
            // 3. 修改库存，根据OrderId，查询出所有的订单商品条目，根据每一个商品的数量，扣减锁定库存
            boolean isStockUpdated = orderCoreService.updateStockStatus(request.getTradeNo());
            if (!isStockUpdated) {
                log.info("更改库存出问题");
                alipayQueryRetResponse.setCode(PayReturnCodeEnum.DB_EXCEPTION.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.DB_EXCEPTION.getMsg());
                return alipayQueryRetResponse;
            }
        } else {
            // 1. 修改tb_payment中的订单支付记录的支付结果 ->PayResultEnum.PAY_FAIL
            alipayQueryRetResponse.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
            alipayQueryRetResponse.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
            return alipayQueryRetResponse;
        }

        // 返回相应的response
        alipayQueryRetResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipayQueryRetResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        return alipayQueryRetResponse;
    }
}
